package com.itheima.test;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Before;


public class testTicket12306 implements Runnable {
    private int tickets=100;

    private InterProcessMutex lock;
    //创建连接

    public testTicket12306(){
        //重试策略
        RetryPolicy retryPolicy= new ExponentialBackoffRetry(3000,10);
        //方式2：链式编程
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.223.129:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .build();

        //开启连接
        client.start();

        //创建锁对象
        lock = new InterProcessMutex(client, "/lock");
    }

    @Override
    public void run() {
        while (true){
            try {
                //获取锁对象
                lock.acquire();
                //开始卖票
                if (tickets>0){

                    System.out.println(Thread.currentThread().getName()+"正在卖第"+tickets+"张票");
                    tickets--;
                    Thread.sleep(200);
                }else {
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
